package com.wenmang.networklib.frame;

import com.wenmang.networklib.utils.LogUtils;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * desc:
 * 1.请求队列添加 网络请求任务
 * 2.线程池处理 网络请求任务
 * <p>
 * author: created by zhoujx on 2018/10/19 14:31
 */
public class WMThreadPoolManager {
    private static final String TAG = "WMThreadPoolManager";
    private static WMThreadPoolManager sInstance = new WMThreadPoolManager();

    // 请求队列
    private LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    // 线程池
    private ThreadPoolExecutor executor;

    private WMThreadPoolManager() {
        executor = new ThreadPoolExecutor(4, 20, 15, TimeUnit.SECONDS, queue, rejectedExecutionHandler);
        executor.execute(runnable);
    }

    private RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
            // TODO: 2018/10/19 增加重试次数控制
            try {
                queue.put(runnable);
            } catch (InterruptedException e) {
                LogUtils.e(TAG, e.getMessage());
            }
        }
    };

    // 线程池任务执行起来
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            while (true) {
                Runnable runnable = null;
                try {
                    runnable = queue.take();
                } catch (InterruptedException e) {
                    LogUtils.e(TAG, e.getMessage());
                }

                if (null != runnable) {
                    executor.execute(runnable);
                }
            }
        }
    };

    // 任务添加至队列
    public void execute(Runnable runnable) {
        if (null != runnable) {
            try {
                queue.put(runnable);
            } catch (InterruptedException e) {
                LogUtils.e(TAG, e.getMessage());
            }
        }
    }

    public static WMThreadPoolManager getInStance() {
        return sInstance;
    }
}
